package thread;

/**
 * 多线程并发安全问题
 * 当多个线程并发操作同一临界资源，由于线程切换时机不确定，导致执行顺序出现混乱，从而引发不良后果。
 * 临界资源:操作该资源的过程同一时刻只能由一条线程进行
 */
public class SyncDemo {
    private static boolean success1 = false;//记录第一个人是否取款成功
    private static boolean success2 = false;//记录第二个人是否取款成功
    public static void main(String[] args) {
        Bank bank = new Bank();
        while (true){
            //模拟两个人一起取钱
            Thread t1 = new Thread(){
                public void run(){
                    success1 = bank.getMoney(20000);
                }
            };
            Thread t2 = new Thread(){
                public void run(){
                    success2 = bank.getMoney(20000);
                }
            };
            t1.start();
            t2.start();
            try {
                Thread.sleep(20);//卡住20毫秒，目的等待t1和t2执行完毕
            } catch (InterruptedException e) {
            }
            if (success1 & success2){
                System.out.println("卡BUG成功！！同时取钱成功");
                break;
            }else{
                System.out.println("正常，只有一人取款成功");
                bank.saveAccount(20000);
                success1= false;
                success2= false;
            }
        }
    }
}

class Bank{
    private int account = 20000;//账号余额2W
    public synchronized boolean getMoney(int money){
        //查询账号余额
        int account = getAccount();
        //判断余额是否充足
        if (account>=money){
            account = account - money;
            Thread.yield();//让线程在这里主动放弃本次剩余时间片，模拟执行到这里时间耗尽发生线程切换
            //重新记账
            saveAccount(account);
            return true;//允许出钞
        }
        return false;//拒绝出钞
    }
    public void saveAccount(int account){
        this.account = account;
    }

    //查询账号余额
    public int getAccount(){
        return account;
    }
}